# 文件操作
# f = open('d:/_Python/Note/test1.txt', 'r')
# print(f)
# print(type(f))
# # f此处表示file的缩写，f是文件对象（是内存的一个变量），用于间接操作硬盘内容
# # r表示read,按照读方式打开
# # w表示write,按照直接写方式打开
# # a表示append,按照追加写方式打开，把内容写到原有文件内容的末尾
# f.close()
import random
from importlib import import_module

# 文件打开个数有上限
# file_list = []
# count = 0
# while True:
#     f = open('d:/_Python/Note/test1.txt', 'r')
#     file_list.append(f)
#     count += 1
#     print(f'打开文件的个数:{count}')

# 写文件
# f = open('d:/_Python/Note/test1.txt', 'w')
# f.write('hello')
# f.close()
#
# f = open('d:/_Python/Note/test1.txt', 'a')
# f.write(' world')
# f.close()

# 读文件
# f = open('d:/_Python/Note/test2.txt', 'r',encoding='utf8')
# result = f.read(2) # 读取两个字符
# print(result)
# f.close()
#
# f = open('d:/_Python/Note/test2.txt', 'r', encoding='utf8')
# serial_number = 1
# for line in f: # 用for循环读取文件时是按行的，文件每一行末尾自带换行符
#     print(f'line{serial_number}: {line}', end='')
#     serial_number += 1
# f.close()
#
# f = open('d:/_Python/Note/test2.txt', 'r', encoding='utf8')
# lines = f.readlines() # readlines是按行读取的方法
# print(lines)
# f.close()
# 文件资源管理器
# 类似C++中的智能指针，Java中的try  with Resources，Golang中的defer
# def func():
#     with open('d:/_Python/Note/test2.txt') as f:
#     # with as 能确保文件在使用完毕后自动关闭，避免了因忘记调用 close() 方法而导致的资源泄漏。
#         lines = f.read()
#         print(lines)



# 标准库的使用
# 实例1：日期计算器
# import datetime
# # 先构造datetime变量
# date1 = datetime.datetime(year=2012, month=2, day=14)
# date2 = datetime.datetime(year=2016, month=2, day=3)
# print(date2 - date1)
#
# from datetime import datetime
# date1 = datetime(year=2012, month=2, day=14)
# date2 = datetime(year=2016, month=2, day=3)
# print(date2 - date1)
#
# import datetime as dt
# date1 = dt.datetime(year=2012, month=2, day=14)
# date2 = dt.datetime(year=2016, month=2, day=3)
# print(date2 - date1)



# 实例2：文件查找工具
# import os # operating system 操作系统
#
# path = input('请输入要搜索的路径：')
# file = input('请输入要搜索的关键词：')
#
# # os.walk效果演示
# # for dir_path, dir_names, filenames in os.walk(path):    # directory 目录
# #     print('----------------------------------')
# #     print(f'dir_path:{dir_path}')
# #     for dir_name in dir_names:
# #         print(dir_name)
# #     for filename in filenames:
# #         print(filename)
#
# for dir_path, _, filenames in os.walk(path):
#     for f in filenames:
#         if file in f:
#             print(f'{dir_path}/{f}')



# 第三方库的使用
# 实例1：二维码生成工具
# import qrcode
# img = qrcode.make('你好，世界')
# img.save("qrcode.png")

# 实例2：操作excel
# import xlrd
# # 1.先打开 xlsx 文件
# xlsx = xlrd.open_workbook('D:\我的/Python/studynote/6.文件/test.xlsx')
# # 2.获取指定的标签页
# table = xlsx.sheet_by_index(0)
# # 3.获取到表格有多少行
# num_rows = table.nrows
# # print(f'number of rows : {num_rows}')
# # 4.进行循环统计操作
# total = 0
# count = 0
# for i in range(1, num_rows):
#     class_id = table.cell_value(i, 1)
#     if 100 == class_id:
#         total += table.cell_value(i, 2)
#         count += 1
# print(f'100班的平均分是{total / count}')

# 实例3：程序猿鼓励师
import random
from pynput import keyboard
from playsound import playsound
from threading import Thread


sound_list = ['sound/birds.mp3','sound/wind.mp3']
count = 0 # 记录用户按键盘的次数


def release_key(key):
    """
    这个函数，在用户释放键盘按键的时候会被调用（属于回调函数 callback functiond]2）
    :param key:用户按的键
    """
    #print(key)
    global count
    count += 1
    if 0 == count % 20:
        i = random.randint(0, len(sound_list)-1)
        # playsound(sound_list[i])
        t = Thread(target=playsound, args=(sound_list[i], )) # 创建一个线程（相当于加一个执行流）
        t.start()


# 当我们创建好 Listener 之后，用户的按键动作就会被捕获到
listener = keyboard.Listener(on_release=release_key)
listener.start()
listener.join()